<!-- eslint-disable camelcase -->
<script setup>
import { useStore } from 'vuex'
import { ref, onMounted, provide, getCurrentInstance, onUnmounted, h } from 'vue'
import axios from 'axios'
import router from '../router/router'
import storage from '../utils/storage'
import SingleRoom from '../components/SingleRoom.vue'
import GroupRoom from '../components/GroupRoom.vue'
import chataiRoom from '../components/chataiRoom.vue'

import { ElNotification } from 'element-plus'

const store = useStore()
const username = ref(store.state.userStore.userInfo.username)
const avatarUrl = ref(store.state.userStore.userInfo.avatarUrl)
const userId = ref(store.state.userStore.userInfo.userId)
const friendlist = ref([])
const ifvisable = ref(false)
const active = ref(-1)
const touser = ref()
const touserId = ref()
const touseravatarUrl = ref()
const groupName = ref()
const AIName = ref()
const groupAvatarUrl = ref()
const ifvisablegroup = ref(false)
const { proxy } = getCurrentInstance()
const users = ref([])
const groups = ref([])
const socket = ref(proxy.$webSocketService.socket)

const params = ref({
  key: ''
})
const showOps = ref(false)
const ops = ref([])
const ops2 = ref([])
const opsIndex = ref(-1)
const userinfo = ref({
  nameinfo: username
})

const maybeFriend = ref([])
const count = ref(0)
const ifAI = ref(false)
const msgsession = ref([])
onMounted(() => {
  socket.value.send(JSON.stringify(userinfo.value))
  getfriend()
  getMsgSession()
  getRecommend()
  sign()
})
onUnmounted(() => {
  closeWebsocket()
})
const sign = () => {
  const isFromLoginPage = sessionStorage.getItem('isFormLoginPage')
  if (isFromLoginPage) {
    console.log(11)
    axios.get('api/usercontroller/sign').then((res1) => {
      axios.get('api/usercontroller/sign/count').then((res2) => {
        if (res1) {
          ElNotification({
            title: '签到成功',
            message: h('i', { style: 'color: teal' }, '你已连续签到' + res2.data + '天')
          })
        }
      })
    })
    sessionStorage.removeItem('isFormLoginPage')
  }
}
const getRecommend = () => {
  axios.post('api/usercontroller/getremmend', {
    userId: userId.value
  }).then(res => {
    maybeFriend.value.push(res.data)
    console.log(maybeFriend.value)
  })
}
const closeWebsocket = () => {
  for (const value in msgsession.value) {
    console.log(msgsession.value[value])
    axios.get('api/session/update/' + value + '/' + username.value + '/' + msgsession.value[value]).then(res => {
      msg.value.push(res.data)
    })
  }
}

socket.value.addEventListener('message', (res) => {
  if ((res.data) !== '用户不在线') {
    const session = (JSON.parse(res.data))
    if (session.fromUser !== touser.value) {
      msgsession.value[session.fromUser]++
    }
  }
})

const msg = ref([])

const getMsgSession = () => {
  axios.get('api/session/queryAll/' + username.value).then(res => {
    msgsession.value = res.data
    console.log(msgsession.value)
    const promises = []
    for (const value in msgsession.value) {
      if (msgsession.value[value] !== 0) {
        const promise = axios.get('api/singlemsgcontroller/getnoread/' + value + '/' + username.value).then(res => {
          msg.value.push(res.data)
          console.log(msg.value)
        })
        promises.push(promise)
      }
    }
    Promise.all(promises).then(() => {
      msg.value.forEach((innnerArray, outerindex) => {
        if (innnerArray.length !== 0) {
          console.log(msg.value[outerindex])
          const name = msg.value[outerindex][0].fromUser
          count.value = count.value + 1
          console.log(count.value)
          sessionStorage.setItem(count.value + name, JSON.stringify(msg.value[outerindex]))
        }
      })
    })
  })
}
provide('count', count)
const getfriend = () => {
  axios.get('api/usercontroller/user/' + userId.value).then(res => {
    friendlist.value = res.data
    axios.get('api/groupcontroller/group/' + username.value).then(res => {
      friendlist.value.push(res.data)
    })
  })
}

const exit = () => {
  closeWebsocket()
  storage.clearAll()
  sessionStorage.clear()
  router.push('/login')
}

const handleKeyUp = (e) => {
  if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 65 && e.keyCode <= 90) || e.keyCode === 8) {
    showOps.value = true
    // 用户输入的字符，需要自动补全
    getSuggestion()
  } else if (e.keyCode === 13) {
    // 用户按回车，需要搜索
    search()
  } else if (e.keyCode === 38) {
    if (opsIndex.value > 0) {
      opsIndex.value--
    } else {
      opsIndex.value = ops.value.length - 1
    }
  } else if (e.keyCode === 40) {
    opsIndex.value = (opsIndex.value + 1) % ops.value.length
  } else if (e.keyCode === 27) {
    params.value.key = ''
    showOps.value = false
  }
}

const getSuggestion = () => {
  if (params.value.key) {
    axios.get('api/usercontroller/suggestion/' + params.value.key).then(res => {
      ops.value = res.data
      axios.get('api/groupcontroller/suggestion/' + params.value.key).then(res => {
        ops2.value = res.data
      })
    })
  } else {
    ops.value = []
    ops2.value = []
  }
}

const handleSearch1 = () => {
  axios.post('api/usercontroller/list', {
    key: params.value.key
  }).then(res => {
    users.value = res.data.users
    touser.value = users.value[0].username
    touseravatarUrl.value = users.value[0].avatarUrl
    touserId.value = users.value[0].userId
    showOps.value = false
    router.push({
      path: '/single',
      query: {
        name: touser.value,
        url: touseravatarUrl.value,
        userId: touserId.value
      }
    })
    console.log(users.value)
  })
}
const handleSearch2 = () => {
  axios.post('api/groupcontroller/list', {
    key: params.value.key
  }).then(res => {
    groups.value = res.data.groups
    touser.value = groups.value[0].groupName
    touseravatarUrl.value = groups.value[0].groupAvatarUrl
    console.log(touseravatarUrl.value)
    showOps.value = false
    router.push({
      path: '/group',
      query: {
        name: touser.value,
        url: groups.value[0].groupAvatarUrl
      }
    })
  })
}

const search = () => {
  axios.post('api/usercontroller/list', {
    key: params.value.key
  }).then(res => {
    users.value = res.data.users
  })
  axios.post('api/groupcontroller/list', {
    key: params.value.key
  }).then(res => {
    console.log(res.data)
    groups.value = res.data.groups
  })
}
const visable = (index) => {
  if (friendlist.value[index].username === 'chatAI') {
    ifvisable.value = false
    ifAI.value = true
    ifvisablegroup.value = false
    active.value = index
    AIName.value = friendlist.value[index].username
    touseravatarUrl.value = friendlist.value[index].avatarUrl
    touserId.value = friendlist.value[index].userId
  } else if (friendlist.value[index].username) {
    ifAI.value = false
    ifvisablegroup.value = false
    ifvisable.value = true
    active.value = index
    touser.value = friendlist.value[index].username
    touseravatarUrl.value = friendlist.value[index].avatarUrl
    touserId.value = friendlist.value[index].userId
    msgsession.value[touser.value] = 0
    console.log(msgsession.value[touser.value])
    updateread()
  }
}
const updateread = () => {
  axios.get('api/singlemsgcontroller/update/' + touser.value + '/' + username.value).then(res => {

  })
}

const visablegroup = (index) => {
  ifvisable.value = false
  ifAI.value = false
  ifvisablegroup.value = true
  active.value = index
  groupName.value = friendlist.value[index].groupName
  groupAvatarUrl.value = friendlist.value[index].groupAvatarUrl
}

const goSpace = () => {
  router.push('/dynamicSpace')
}

provide('touser', touser)
provide('touseravatarUrl', touseravatarUrl)
provide('groupName', groupName)
provide('temmsg', msg)
provide('AIName', AIName)

</script>

<template>
  <el-container class="home_container">

    <el-header id="topbar">
      <el-row>
        <el-col :span="4" class="topbar-left">
          <span class="title" @click="index()">IM-SYSTEM</span>
        </el-col>
        <el-col :span="20" class="topbar-right">
          <div class="search-bar">
            <div class="input-box">
              <input title="输入关键字搜索" v-model="params.key" type="text" @click.stop="" @focus="showOps = true"
                @keyup="handleKeyUp($event)">
              <button @click="handleSearch">搜索</button>
            </div>
            <div class="complete-box" v-show="showOps && ops.length > 0 || ops2.length > 0">
              <div class="point">人</div>
              <div v-for="(item, i) in ops" :key="i" @click="handleSearch1()" @mouseover="opsIndex = i, params.key = item"
                :style='{ "background-color": opsIndex === i ? "#FFC0CB" : "#fff" }'>{{ item }}
              </div>
              <div class="point2">组</div>
              <div v-for="(item, i) in ops2" :key="i" @click="handleSearch2()"
                @mouseover="opsIndex = i, params.key = item"
                :style='{ "background-color": opsIndex === i ? "#FFC0CB" : "#fff" }'>{{ item }}
              </div>
            </div>
          </div>
          <i class="el-icon-menu" @click="toggle()"></i>
          <div class="user">
            <img :src="'src/' + avatarUrl" class="user-img" ref="img" @click="showSetting()" />
            <li class="right">
              <el-dropdown>
                <span>
                  <div class="box"> <a href="javacript:;">{{ username }}</a></div>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <p @click="manage()">管理中心</p>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <p class="exit" @click="exit()">退出</p>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </li>
          </div>
        </el-col>
      </el-row>
    </el-header>

    <el-container>
      <el-aside width="200px" class="left">
        <div class="left3">
          <el-col>
            <el-menu default-active="2" background-color="#94b6e3" class="el-menu-vertical-demo" @open="handleOpen"
              @close="handleClose">
              <el-sub-menu index="1">
                <template #title>
                  <span class="left1">好友</span>
                </template>
                <el-menu-item-group>
                  <div class="aside" :class="active != index ? 'aside1' : 'aside2'" v-for="(item, index) in friendlist"
                    :key="index" @click="visable(index)" v-show="item.username">
                    <div class="img"><img :src="'src/' + item.avatarUrl" class="friend-img" ref="img" /></div>
                    <div class="username">{{ item.username }}</div>
                    <div class="noread" v-show="msgsession[item.username] >= 1">{{ msgsession[item.username]
                    }}</div>
                  </div>

                  <div class="aside" :class="active != index ? 'aside1' : 'aside2'" v-for="(item, index) in  friendlist"
                    :key="index" @click="visablegroup(index)" v-show="item.groupName">
                    <div class="img"><img :src="'src/' + item.groupAvatarUrl" class="friend-img" ref="img" /></div>
                    <div class="username">组：{{ item.groupName }}</div>
                  </div>
                </el-menu-item-group>
              </el-sub-menu>
            </el-menu>
          </el-col>
        </div>

        <div class="left2" @click="goSpace">动态空间</div>
        <div class="newfriend">
          <div class="left3">
            <el-col>
              <el-menu default-active=" 2" background-color="#94b6e3" class="el-menu-vertical-demo" @open="handleOpen"
                @close="handleClose">
                <el-sub-menu index="1">
                  <template #title>
                    <span class="left1">可能认识的人</span>
                  </template>
                  <el-menu-item-group>
                    <div class="aside" :class="active != index ? 'aside1' : 'aside2'"
                      v-for="(item, index) in maybeFriend[0]" :key="index" @click="visable(index)" v-show="item.username">
                      <div class="img"><img :src="'src/' + item.avatarUrl" class="friend-img" ref="img" /></div>
                      <div class="username">{{ item.username }}</div>
                      <div class="noread" v-show="msgsession[item.username] >= 1">{{ msgsession[item.username]
                      }}</div>
                    </div>
                  </el-menu-item-group>
                </el-sub-menu>
              </el-menu>
            </el-col>
          </div>

        </div>
      </el-aside>
      <el-main v-show="ifvisable">
        <SingleRoom></SingleRoom>
      </el-main>
      <el-main v-show="ifvisablegroup">
        <GroupRoom></GroupRoom>
      </el-main>
      <el-main v-show="ifAI">
        <chataiRoom></chataiRoom>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
.box {
  padding-bottom: 10px;
  padding-top: 5px;
}

.box a {
  color: #000;
}

.index {
  margin-left: 70px;

}

.home_container {
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%
}

.box {
  margin-top: 25px;

}

.box a {
  text-decoration: none;
  font-size: x-large;
  color: aquamarine;
}

.right .icon {
  margin-right: 6px;

}

#topbar {
  position: relative;
  z-index: 10;
  background-color: #124280;
  height: 80px;
  line-height: 80px;
  color: #fff;
  box-shadow: 5px 0px 10px rgba(0, 0, 0, 0.5);
}

#topbar .topbar-left {
  height: 80px;
  display: flex;
  justify-content: center;
  background: rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.topbar-left .icon-kaoshi {
  font-size: 60px;
}

.topbar-left .title {
  font-size: 20px;
  cursor: pointer;
}

.search-bar {
  display: flex;
  margin-left: 300px;
  margin-right: 50px;
}

.input-box {
  display: flex;
  height: 28px;
}

.search-bar input {
  border: 1px solid #F80;
  vertical-align: top;
  border-radius: .25rem 0 0 .25rem;
  width: 300px;
}

.search-bar button {
  border: 1px solid #F80;
  background-color: #F80;
  color: #fff;
  border-radius: 0 .25rem .25rem 0;
  height: 28px;
}

.complete-box {
  margin-top: 28px;
  position: absolute;
  z-index: 99;
  text-align: left;
  border: 1px solid #f1f1f2;
  width: 293px;
  background-color: #fff;
}

#topbar .point {

  background-color: #cff4e4;
  height: 45px;
  padding-bottom: 0px;
  padding-left: 120px;
}

#topbar .point2 {
  background-color: #cff4e4;
  height: 45px;
  padding-bottom: 0px;
  padding-left: 120px;
  border-top: 1px solid black;
}

.complete-box div {
  padding-left: 7px;
  color: black;
  font-size: small;
  vertical-align: top;
  height: 50px;
}

#topbar .topbar-right {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.topbar-right .user-img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.topbar-right .el-icon-menu {
  font-size: 30px;
  margin-left: 20px;
}

.topbar-right .user {
  position: relative;
  margin-right: 40px;
  display: flex;
}

.topbar-right .user .user-img {
  margin-top: 15px;
  margin-left: 10px;
  cursor: pointer;
}

.user .out {
  font-size: 14px;
  position: absolute;
  top: 80px;
  right: 0px;
  background-color: #fff;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  padding: 12px;
}

.user .out ul {
  list-style: none;
}

.user .out ul>li {
  height: 26px;
  line-height: 26px;
}

.left {
  background-color: #bcd2ee;
  width: 210px;
}

.left2 {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  background-color: #94e395;
  width: 210px;
}

.left3 {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e3c794;
  width: 210px;
}

.newfriend {
  justify-content: center;
  align-items: center;
  margin-top: 40px;
  height: 80px;

}

.left1 {
  height: 50px;
  text-align: center;
  background-color: #94b6e3;
  width: 220px;
  color: rgb(218, 116, 44);
}

.aside1 {
  border-bottom: solid 0.5px rgba(0, 0, 0, 0.066);
  height: 80px;
  text-align: center;

  display: flex;
}

.aside2 {
  background-color: #9b3838;
  border-bottom: solid 0.5px rgba(0, 0, 0, 0.066);
  height: 80px;
  text-align: center;
  display: flex;
}

.friend-img {
  flex: 1;
  width: 95px;
  height: 80px;
}

.username {
  flex: 1;
  text-align: left;
  padding-left: 25px;
  margin-top: 10px;
  width: 15px;
}

.noread {
  margin-top: 25px;
  margin-bottom: 20px;
  background-color: #e75050;
  border-radius: 50%;
  text-align: center;
  padding-top: 6.5px;
  width: 30px;
}
</style>
